#include "StdAfx.h"
#include "RibbonColorSetter.h"
#include <UIRibbonPropertyHelpers.h>
#include "shlwapi.h"


CRibbonColorSetter::CRibbonColorSetter(void)
{
}

CRibbonColorSetter::~CRibbonColorSetter(void)
{
}

HRESULT STDMETHODCALLTYPE CRibbonColorSetter::Execute( 
    UINT32 commandId,
    UI_EXECUTIONVERB verb,
	const PROPERTYKEY *key,
    const PROPVARIANT *currentValue,
    IUISimplePropertySet *commandExecutionProperties)
{
	UI_SWATCHCOLORTYPE uType = 
			(UI_SWATCHCOLORTYPE)PropVariantToUInt32WithDefault(*currentValue, UI_SWATCHCOLORTYPE_NOCOLOR);

    COLORREF color = 0;;
	bool bUseOriginalColors = false;

    switch(uType)
    {
      case UI_SWATCHCOLORTYPE_RGB:
        PROPVARIANT var;
        commandExecutionProperties->GetValue(UI_PKEY_Color, &var);
        color = PropVariantToUInt32WithDefault(var, 0);
        break;
      case UI_SWATCHCOLORTYPE_AUTOMATIC:
        bUseOriginalColors = true;
        break;
      case UI_SWATCHCOLORTYPE_NOCOLOR: //No color should be disable by the Ribbon XML
        color = RGB(255,255,255); 
        break;
    }

	UI_HSBCOLOR hsbColor = (verb == UI_EXECUTIONVERB_CANCELPREVIEW) ? _currentColor :
							(bUseOriginalColors) ? _originalColor : ConvertRGBToHSB(color);
	
	HRESULT hr = SetRibbonColor(hsbColor);
	if (FAILED(hr))
		return hr;

	if (verb == UI_EXECUTIONVERB_EXECUTE)
	{
		_currentColor = hsbColor;
	}

	return hr;
}


STDMETHODIMP CRibbonColorSetter::Initialize(REFPROPERTYKEY propertyKey, CComPtr<IUIFramework> pUIFramework) 
{
	_pUIFramework = pUIFramework;
	_propertyKey = propertyKey; 
	CComPtr<IPropertyStore> pPropertyStore;

	//Read the Ribbon original value and store them
	HRESULT hr = _pUIFramework->QueryInterface(&pPropertyStore);
	if (FAILED(hr))
		return hr;
	
	PROPVARIANT propvarColor;
	 
	pPropertyStore->GetValue(_propertyKey, &propvarColor);
	UIPropertyToUInt32(_propertyKey, propvarColor, (UINT *)&_originalColor);
	_currentColor = _originalColor;

	return S_OK;
}

HRESULT CRibbonColorSetter::SetRibbonColor(UI_HSBCOLOR color)
{
	CComPtr<IPropertyStore> propertyStore;

	if (FAILED(_pUIFramework->QueryInterface(&propertyStore)))
		return E_FAIL;
	
	PROPVARIANT propVariantColor;
		
	InitPropVariantFromUInt32(color, &propVariantColor) ;
  
	HRESULT hr = propertyStore->SetValue(_propertyKey, propVariantColor);
	if (FAILED(hr))
		return hr;

	return propertyStore->Commit();
}



UI_HSBCOLOR CRibbonColorSetter::ConvertRGBToHSB(COLORREF color)
{
	WORD wHue, wLuminance, wSaturation;

	ColorRGBToHLS(color, &wHue, &wLuminance, &wSaturation);
	return UI_HSB( (BYTE)wHue, (BYTE)wSaturation, (BYTE)wLuminance);
}